<template>
  <div class="app-container inventory-page-container">
    <div class="category-panel">
      <el-tree
        class="filter-tree"
        :data="categoryList"
        :props="defaultProps"
        node-key="cinvccode"
        default-expand-all
        highlight-current
        :filter-node-method="filterNode"
        @node-click="handleCategoryClick"
        ref="tree"
      >
        <span slot-scope="{ node }">
          <span>{{ node.label }}</span>
        </span>
      </el-tree>
    </div>

    <!-- Right: Inventory List -->
    <div class="inventory-panel">
      <el-form :inline="true" :model="searchForm"   style="margin: 0px;"  class="search-form" @submit.native.prevent>
        <el-form-item label="品名:">
          <el-input v-model="searchForm.cinvname" placeholder="请输入商品名称" clearable/>
        </el-form-item>
        <el-form-item label="规格:">
          <el-input v-model="searchForm.cinvstd" placeholder="请输入规格" clearable/>
        </el-form-item>
        <el-form-item label="库存数量:">
          <el-select v-model="searchForm.searchValue" clearable style="width: 96px;">
            <el-option value=">"></el-option>
            <el-option value=">="></el-option>
            <el-option value="="></el-option>
            <el-option value="<="></el-option>
            <el-option value="<"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input-number
            v-model="searchForm.num"
            :min="0"
            :step="1"
            :controls="true"
            placeholder="数量"
            style="width: 110px; margin-left: 8px;"
          />
        </el-form-item>
        <el-form-item label="商品编码">
          <el-input v-model="searchForm.cinvcode" placeholder="请输入商品编码" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="inventoryList" border    style="width: 100%;  table-layout: fixed;" @row-dblclick="handleRowDblClick">
        <el-table-column prop="cinvcode" label="编码" align="left"  width="150" />
        <el-table-column prop="cinvname" label="品名" align="left"  width="400" />
        <el-table-column prop="cinvstd" label="规格" align="left"  width="340"  />
        <el-table-column prop="comunitname" label="单位" align="left"  width="120" />
        <el-table-column prop="saleprice" label="单价" align="left"    width="120" />
        <el-table-column prop="num" label="库存" align="left"   width="120"   />
        <el-table-column label="订购数量" align="left"  width="250" class-name="col-order">
          <template slot-scope="scope">
            <div class="order-action-row">
              <el-input-number
                v-model="scope.row.orderNum"
                :min="0"
                :max="scope.row.num"
                :step="1"
                :controls="true"
                placeholder="请输入数量"
                style="width: 120px; margin-right: 8px;"
              />
              <el-button
                type="primary"
                size="mini"
                @click="addToCart(scope.row, $event, scope.$index)"
                :disabled="(scope.row.num === 0) || isShowcar==false  "
                style="width: 80px;"
                :ref="'addCartBtn' + scope.$index"
              >加入购物车</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页和购物车按钮同一行 -->
      <el-row type="flex" justify="space-between" align="middle" style="margin-top: 10px;">
        <el-col  v-show="isShowcar">
          <el-button type="primary" @click="showCart = true" ref="cartBtn">我的购物车,共{{totalNum}} 件商品</el-button>
        </el-col>
        <el-col>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getInventoryList"
          />
        </el-col>
      </el-row>

      <!-- 购物车弹窗 -->
      <el-dialog
        title="我的购物车'"
        :visible.sync="showCart"
        width="90%"
        append-to-body>
        <Cardetail     :isDialog="true"   :isAddRow="false" />
      </el-dialog>

    </div>

  </div>

</template>

<script>
import {listInventoryClass} from "@/api/business/InventoryClass";
import {listInventory,saveCar} from "@/api/business/Inventory";
import Pagination from '@/components/Pagination';
import {listCardetail} from "@/api/business/cardetail";
import Cardetail from "@/views/business/cardetail/index.vue";

export default {
  name: "Inventory",
  components: {Pagination,Cardetail},
  props: {
    isShowcar: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {
      // Category Tree
      filterText: '',
      categoryList: [],
      defaultProps: {
        children: "children",
        label: "cinvcname"
      },
      inventoryList: [],
      carList:[],
      total: 0,
      totalNum: 0,
      loading: true,
      // Query Params
      queryParams: {
        pageNum: 1,
        pageSize: 10, // 3 rows of 4 items
        cinvccode: null // For filtering by category
      },
      // Search Form
      searchForm: {
        cinvname: '',
        cinvstd: '',
        num: '',
        cinvcode: ''
      },
      showCart: false,
      // 用props初始化本地变量，保证响应式
      showCarBtn: this.isShowcar
    };
  },
  created() {
    debugger;
    this.getCategoryList();
    this.getInventoryList();
    this.getCarList();
  },
  methods: {
    /** Fetch Category List */
    getCategoryList() {
      listInventoryClass({pageNum: 1, pageSize: 9999}).then(response => {
        // We need a tree structure, assuming the backend provides children.
        // If not, a handleTree function is needed.
        this.categoryList = response.rows;
      });
    },

    /** Fetch Inventory List */
    getInventoryList() {
      this.loading = true;
      listInventory(this.queryParams).then(response => {
        this.inventoryList = response.rows.map(item => ({...item, orderNum: 1}));
        this.total = response.total;
        this.loading = false;
      });
    },
    getCarList() {
      this.loading = true;
      listCardetail(this.queryParams).then(response => {
        this.carList = response.rows;
        this.totalNum = this.carList.reduce((sum, item) => sum + (parseFloat(item.orderNum) || 0), 0);
        this.loading = false;
      });
    },

    /** Handle Category Click */
    handleCategoryClick(data) {
      this.queryParams.cinvccode = data.cinvccode;
      this.queryParams.pageNum = 1;
      this.getInventoryList();
    },

    /** Filter tree nodes */
    filterNode(value, data) {
      if (!value) return true;
      return data.cinvcname.indexOf(value) !== -1;
    },
    // 查询和重置方法
    handleSearch() {
      debugger;
      this.queryParams = {
        ...this.queryParams,
        ...this.searchForm,
        pageNum: 1
      };
      this.getInventoryList();
      this.getCarList();

    },
    handleReset() {
      this.searchForm = {
        cinvname: '',
        cinvstd: '',
        num: '',
        cinvcode: ''
      };
      this.handleSearch();
    },
    addToCart(item, event, idx) {
      // 1. 先处理购物车数据
      const index = this.carList.findIndex(x => x.cinvcode == item.cinvcode);
      if (index > -1) {
        const oldNum = parseFloat(this.carList[index].orderNum) || 0;
        const addNum = parseFloat(item.orderNum) || 0;
        this.carList[index].orderNum = oldNum + addNum;
      } else {
        this.carList.push({...item});
      }

      saveCar(this.carList);
      // 立即同步统计总数
      this.totalNum = this.carList.reduce((sum, item) => sum + (parseFloat(item.orderNum) || 0), 0);

      // 2. 再做动画
      let addBtnRef = this.$refs['addCartBtn' + idx];
      let addBtn = Array.isArray(addBtnRef) ? addBtnRef[0] : addBtnRef;
      if (addBtn && addBtn.$el) addBtn = addBtn.$el;
      const cartBtn = this.$refs.cartBtn.$el || this.$refs.cartBtn;
      const startRect = addBtn.getBoundingClientRect();
      const endRect = cartBtn.getBoundingClientRect();
      const ballSize = 18;
      const ball = document.createElement('div');
      ball.className = 'cart-fly-ball';
      ball.style.position = 'fixed';
      ball.style.left = (startRect.left + startRect.width / 2 - ballSize / 2) + 'px';
      ball.style.top = (startRect.top + startRect.height / 2 - ballSize / 2) + 'px';
      document.body.appendChild(ball);
      ball.offsetWidth;
      setTimeout(() => {
        ball.style.left = (endRect.left + endRect.width / 2 - ballSize / 2) + 'px';
        ball.style.top = (endRect.top + endRect.height / 2 - ballSize / 2) + 'px';
        ball.style.transform = 'scale(0.8)';
      }, 20);
      // 只移除当前小球
      const removeBall = () => {
        if (ball && ball.parentNode) {
          ball.parentNode.removeChild(ball);
        }
        ball.removeEventListener('transitionend', removeBall);
      };
      ball.addEventListener('transitionend', removeBall);
    },
    handleRowDblClick(row) {
      this.$emit('rowDbclick', row);
    }
  }
};
</script>

<style  lang="scss" scoped>
.inventory-page-container {
  display: flex;
  height: 100%;
}

.category-panel {
  width: 130px;
  min-width: 130px;
  border-right: 1px solid #e6ebf5;
  padding-right: 20px;
  overflow-y: auto;
}

.inventory-panel {
  flex: 1;
  padding-left: 20px;

}

.image-slot .el-icon-picture-outline {
  font-size: 30px;
  margin-bottom: 10px;
}


.inventory-row label {
  font-weight: bold;
  margin-right: 4px;
  white-space: nowrap;
}


.search-form {
  margin: 10px 0;
}

.order-action-row {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
}



</style>
<style  lang="scss">


.cart-fly-ball {
  position: fixed;
  z-index: 99999;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #ff9800;
  border: 2px solid #333;
  box-shadow: 0 2px 8px rgba(255,152,0,0.3);
  pointer-events: none;
  transition: left 0.7s cubic-bezier(.49,-0.29,.75,.41), top 0.7s cubic-bezier(.49,-0.29,.75,.41), transform 0.7s;
}

.el-table .cell{
  height: 30px;
}


</style>
